import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';

import '../../../models/product.dart';
import '../../../services/auth_service.dart';
import '../../../services/product_service.dart';

class AddProductLogic extends GetxController {
  final AuthService _authService = AuthService();
  final ProductService _productService = ProductService();

  final nameController = TextEditingController();
  final descriptionController = TextEditingController();
  final priceController = TextEditingController();
  final stockController = TextEditingController();

  final isLoading = false.obs;
  final ImagePicker _imagePicker = ImagePicker();
  final Rx<File?> selectedImage = Rx<File?>(null);

  @override
  void onClose() {
    nameController.dispose();
    descriptionController.dispose();
    priceController.dispose();
    stockController.dispose();
    super.onClose();
  }

  Future<void> pickImage(ImageSource source) async {
    try {
      final XFile? pickedFile = await _imagePicker.pickImage(
        source: source,
        imageQuality: 80, // 压缩图片质量以减小文件大小
      );

      if (pickedFile != null) {
        selectedImage.value = File(pickedFile.path);
      }
    } catch (e) {
      SmartDialog.showToast('选择图片失败: $e');
    }
  }

  void showImagePickerOptions() {
    Get.bottomSheet(
      Container(
        color: Colors.white,
        child: Wrap(
          children: [
            ListTile(
              leading: Icon(Icons.photo_camera),
              title: Text('拍照'),
              onTap: () {
                Get.back();
                pickImage(ImageSource.camera);
              },
            ),
            ListTile(
              leading: Icon(Icons.photo_library),
              title: Text('从相册选择'),
              onTap: () {
                Get.back();
                pickImage(ImageSource.gallery);
              },
            ),
            if (selectedImage.value != null)
              ListTile(
                leading: Icon(Icons.delete, color: Colors.red),
                title: Text('删除当前图片', style: TextStyle(color: Colors.red)),
                onTap: () {
                  Get.back();
                  selectedImage.value = null;
                },
              ),
          ],
        ),
      ),
    );
  }

  // 保存图片到应用文件夹
  Future<String?> _saveImageToAppDirectory(File imageFile) async {
    try {
      final appDir = await getApplicationDocumentsDirectory();
      final fileName = 'product_${DateTime.now().millisecondsSinceEpoch}.jpg';
      final savedImage = await imageFile.copy('${appDir.path}/$fileName');
      return savedImage.path;
    } catch (e) {
      SmartDialog.showToast('保存图片失败: $e');
      return null;
    }
  }

  Future<void> saveProduct() async {
    if (nameController.text.isEmpty ||
        descriptionController.text.isEmpty ||
        priceController.text.isEmpty ||
        stockController.text.isEmpty) {
      SmartDialog.showToast('请填写所有必填字段');
      return;
    }

    // Validate price and stock
    double? price = double.tryParse(priceController.text);
    int? stock = int.tryParse(stockController.text);

    if (price == null || price <= 0) {
      SmartDialog.showToast('请输入有效的价格');
      return;
    }

    if (stock == null || stock < 0) {
      SmartDialog.showToast('请输入有效的库存数量');
      return;
    }

    isLoading.value = true;

    try {
      final userId = await _authService.getCurrentUserId();
      if (userId == null) {
        SmartDialog.showToast('用户未登录');
        return;
      }

      // 如果有选择图片，则保存到应用文件夹
      String? imagePath;
      if (selectedImage.value != null) {
        imagePath = await _saveImageToAppDirectory(selectedImage.value!);
      }

      final product = Product(
        name: nameController.text.trim(),
        description: descriptionController.text.trim(),
        price: price,
        stock: stock,
        imageUrl: imagePath,
        publisherId: userId,
      );

      await _productService.insertProduct(product);
      SmartDialog.showToast('商品添加成功');
      Get.back();
    } catch (e) {
      SmartDialog.showToast('添加失败: $e');
    } finally {
      isLoading.value = false;
    }
  }
}
